//
//  AIActionView.m
//  AIActionViewDemo
//
//  Created by telen on 2016/10/12.
//  Copyright © 2016年 telen. All rights reserved.
//

#import "AIActionView.h"

@interface AIActionView()<CAAnimationDelegate>
@property(nonatomic,weak)UIView* superView;
@end

@implementation AIActionView
{
    NSTimer* timer;
    NSTimeInterval countTime;
    BOOL toMove;
}

+ (instancetype)aiActionViewWidthSize:(CGSize)size superView:(UIView *)superView
{
    if (!superView) {
        return nil;
    }
    AIActionView* aiview = [[AIActionView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    aiview.superView = superView;
    [superView addSubview:aiview];
    return aiview;
}

- (void)showRandom_movingRandom
{
    self.center = [self randomPoint_in_superView];
    [self springIn];
    [self move];
}

- (void)unShow_and_remove
{
    toMove = YES;
    [self resumeAni];
    [self springOut];
}

- (BOOL)isanimating
{
    return self.layer.speed != 0.0;
}

- (void)pauseAni
{
    [timer setFireDate:[NSDate distantFuture]];
    CFTimeInterval pausedTime = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    self.layer.speed = 0.0;
    self.layer.timeOffset = pausedTime;
}

- (void)resumeAni
{
    [timer setFireDate:[NSDate date]];
    CFTimeInterval pausedTime = [self.layer timeOffset];
    self.layer.speed = 1.0;
    self.layer.timeOffset = 0.0;
    self.layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    self.layer.beginTime = timeSincePause;
}

#pragma mark-
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        [self addSubview:_contentView];
        //
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside];
        btn.frame = _contentView.frame;
        [self addSubview:btn];
        //
        self.movePod = 50;
        self.unShowTil = 60;
        timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
    }
    return self;
}

- (void)tick:(NSTimer*)tmr
{
    self.center = self.layer.presentationLayer.position;
    countTime += tmr.timeInterval;
    if (!toMove && countTime > self.unShowTil && !(self.keepForPause && !self.isanimating)) {
        [self unShow_and_remove];
    }
}

- (void)dealloc
{
    if(timer)[timer invalidate],timer=nil;
}

#pragma mark-
/**点击*/
- (void)tap:(UITapGestureRecognizer*)tap
{
    if (self.clicked_tapCallBack) {
        self.clicked_tapCallBack(self);
    }
    //NSLog(@"tap:::");
}

/**弹入*/
- (void)springIn
{
    self.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
    [UIView animateWithDuration:0.6 delay:0 usingSpringWithDamping:0.1 initialSpringVelocity:0.9 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.transform = CGAffineTransformMakeScale(1.0, 1.0);
    } completion:^(BOOL finished) {
        [self springbit];
    }];
}

/**弹入*/
- (void)springOut
{
    [UIView animateWithDuration:0.6 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
        self.alpha = 0;
    } completion:^(BOOL finished) {
        if(self.superview)[self removeFromSuperview];
        if (self.did_unShow_and_remove) {
            self.did_unShow_and_remove(self);
        }
    }];
    
//    [UIView animateWithDuration:0.6 delay:0.6 usingSpringWithDamping:0.1 initialSpringVelocity:0.9 options:UIViewAnimationOptionCurveEaseInOut animations:^{
//        self.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
//    } completion:^(BOOL finished) {
//        if(self.superview)[self removeFromSuperview];
//        if (self.did_unShow_and_remove) {
//            self.did_unShow_and_remove(self);
//        }
//    }];
}

- (void)springbit
{
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.contentView.transform = CGAffineTransformMakeScale(0.8, 0.8);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.contentView.transform = CGAffineTransformMakeScale(1.0, 1.0);
        } completion:^(BOOL finished) {
            [self springbit];
        }];
    }];
}

/**移动*/
- (void)move
{
    UIBezierPath* bezier = [UIBezierPath bezierPath];
    [bezier moveToPoint: self.center];
    [bezier addCurveToPoint: [self randomPoint_in_superView] controlPoint1: [self randomPoint_in_superView]controlPoint2: [self randomPoint_in_superView]];
    [bezier addCurveToPoint: [self randomPoint_in_superView] controlPoint1: [self randomPoint_in_superView]controlPoint2: [self randomPoint_in_superView]];
    [bezier addCurveToPoint: [self randomPoint_in_superView] controlPoint1: [self randomPoint_in_superView]controlPoint2: [self randomPoint_in_superView]];
    [bezier addCurveToPoint: [self randomPoint_in_superView] controlPoint1: [self randomPoint_in_superView]controlPoint2: [self randomPoint_in_superView]];
    [self moveTo:bezier duration:3*4];
}
- (void)moveTo:(UIBezierPath*)bezierPath duration:(CGFloat)secord;
{
    CAKeyframeAnimation *moveAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    moveAnimation.duration = secord;
    moveAnimation.path = bezierPath.CGPath;
    moveAnimation.fillMode = kCAFillModeForwards;
    moveAnimation.removedOnCompletion = NO;
    moveAnimation.delegate = self;
    [self.layer addAnimation:moveAnimation forKey:@"moveAnimation"];
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self move];
    });
}

/**随机获得点*/
- (CGPoint)randomPoint_in_superView
{
    if (self.superView) {
        long pod = self.movePod;
        long w = floor(self.superView.bounds.size.width);
        long h = floor(self.superView.bounds.size.height);
        CGFloat x = (random()%(w-pod*2)+pod);
        CGFloat y = (random()%(h-pod*2)+pod);
        return CGPointMake(x, y);
    }
    return CGPointZero;
}

/**随机获得点 view外*/
- (CGPoint)randomPoint_out_superView
{
    if (self.superView) {
        long pod = self.movePod;
        long w = floor(self.superView.bounds.size.width);
        long h = floor(self.superView.bounds.size.height);
        CGFloat x = (random()%(w-pod*2)+pod);
        CGFloat y = (random()%(h-pod*2)+pod);
        
        return CGPointMake(x, y);
    }
    return CGPointZero;
}


@end
